package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * @version 1.0
 * @description 说明
 * @package com.zzyl.nursing.service.impl
 */
@Service
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;

    /**
     * 获取openid
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenid(String code) {
        HttpResponse res = HttpUtil.createGet(OPENID_URL)
                .form("appid", appid)
                .form("secret", secret)
                .form("js_code", code)
                .execute();
        if (res.isOk()) {
            String openId = JSON.parseObject(res.body()).getString("openid");
            if(StrUtil.isNotEmpty(openId)) {
                return openId;
            }
        }
        throw new ServiceException("获取用户的openId失败");
    }

    /**
     * 获取手机号
     *
     * @param detailCode
     * @return
     */
    @Override
    public String getPhone(String detailCode) {
        Map<String,String> map = new HashMap<>();
        map.put("code", detailCode);
        HttpResponse res = HttpUtil.createPost(PHONE_URL+getAccessToken())
                .body(JSON.toJSONString(map))
                .execute();
        if (res.isOk()) {
            JSONObject jsonObject = JSON.parseObject(res.body());
            String phone = (String) jsonObject.getByPath("phone_info.purePhoneNumber");
            if(StrUtil.isNotEmpty(phone)) {
                return phone;
            }
        }
        throw new ServiceException("获取手机号码失败");
    }

    /**
     * 获取微信的临时授权，access_token有效期为2小时 优化：存入redis设置有效期1小50分钟
     * @return
     */
    private String getAccessToken(){
        HttpResponse res = HttpUtil.createGet(TOKEN_URL)
                .form("appid", appid)
                .form("secret", secret)
                .execute();
        if (res.isOk()) {
            String accessToken = JSON.parseObject(res.body()).getString("access_token");
            // 有效期是2小时，存入redis
            if(StrUtil.isNotEmpty(accessToken)) {
                return accessToken;
            }
        }
        throw new ServiceException("获取小程序授权失败");
    }
}
